import React, { useEffect, useState } from 'react'
import axios from 'axios'
import '../component/List.css'
import { useNavigate } from 'react-router-dom'
export default function List() {
  // 定义数据
  const [list, setList] = useState([])
  const [cate, setCate] = useState([])
  const [manner, setManner] = useState([])
  // const [c,setC] = useState('')
  let c = ''
  let m = ''
  // const [m,setM] = useState('')
  const Navigate = useNavigate()
  console.log(c);


  const getList = async () => {
    let { data: { code, list } } = await axios.get('/list', { params: { cate: c, manner: m } })
    if (code === 200) {
      setList(list)
    }
  }

  const getCate = async () => {
    let { data: { code, cate } } = await axios.get('/cate')
    if (code === 200) {
      setCate(cate)
    }
  }

  const getManner = async () => {
    let { data: { code, manner } } = await axios.get('/manner')
    if (code === 200) {
      setManner(manner)
    }
  }

  const near = () => {
    console.log('a');
    
    let arr = [...list]
    arr.sort((a, b) => a.distance - b.distance)
    setList(arr)
  }

  const E = (name) => {
    Navigate(`/Edit?name=${name}`)
  } 




  // 挂载
  useEffect(() => {
    getCate()
    getList()
    getManner()
  }, [])



  return (
    <div>
      <div className='topBox'>
        美团点餐
      </div>
      <div className='middleBox'>
        <div>
          <select
            className='onO'
            onChange={() => near()}
          >
            <option>默认排序</option>
            <option >离我最近</option>
          </select>
          <select
            className='SeC'
            onChange={(i) => {
              c = i.target.value
              getList()
            }}
          >
            {
              cate.map((item) => {
                return <option key={item._id} value={item._id}>{item.name}</option>
              })
            }
          </select>
        </div>
        <div>
          <select
            className='seM'
            onChange={(i) => {
              m = i.target.value
              getList()
            }}
          >
            {
              manner.map((item) => {
                return <option key={item._id} value={item._id}>{item.name}</option>
              })
            }
          </select>
        </div>
      </div>


      <div className='listBigBox'>
        {
          list.map((item) => {
            return <div key={item._id} className='listbox' onClick={()=>E(item.name)}>
              <div><img src={item.img} width={80} height={80}></img></div>
              <div>
                <p className='itemName'>{item.name}</p>
                <p className='itemDistance'>{item.distance}km</p>
              </div>
            </div>
          })
        }
      </div>
    </div>
  )
}
